package org.iryshka.skyserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.iryshka.logit.ConsoleFileLogger;

public class SkyWebServer {
	
	private static List<SkyThread> listSkyThread = new ArrayList<SkyThread>();
	private static List<Socket> socketQueue = new ArrayList<Socket>();
	
	public static synchronized void notifyThreadCompleted(final SkyThread thread) {
		listSkyThread.remove(thread);
		
		if (!socketQueue.isEmpty() && listSkyThread.size() < ConfigAnalyzer.getNumRequests()) {
			final SkyThread newST = new SkyThread(socketQueue.remove(0));
			listSkyThread.add(newST);
			ConsoleFileLogger.logIt("Created a new thread");
			newST.start();
		}
	}
	
	public static synchronized void socketConnected(final Socket clientSock) {
		if (listSkyThread.size() < ConfigAnalyzer.getNumRequests()) {
			final SkyThread newST = new SkyThread(clientSock);
			listSkyThread.add(newST);
			newST.start();
		} else {
			socketQueue.add(clientSock);
		}
	}
	
	private static boolean checkIpBan(final Socket clientSock) {
		if (ConfigAnalyzer.getListOfForbiddenIP() != null) {
			if (ConfigAnalyzer.getListOfForbiddenIP().contains(clientSock.getInetAddress().toString())) {
				ConsoleFileLogger.logIt("The IP adress " + clientSock.getInetAddress() + " has been rejected");
				return true;
			}
		}
		return false;
	}
	
	public static void main(final String[] args) {
		
		try {
			try {
				new ConfigAnalyzer().parseConfigFile(args);
			} catch (final Exception ce) {
				ConsoleFileLogger.logIt("Failed to load program configuration. " + ce.getMessage()
				        + " Leaving program...");
				return;
			}
			
			while (true) {
				
				try (ServerSocket socketToAccept = new ServerSocket(ConfigAnalyzer.getPort())) {
					
					final Socket clientSock = socketToAccept.accept();
					if (checkIpBan(clientSock)) {
						clientSock.close();
						continue;
					}
					socketConnected(clientSock);
					
					ConsoleFileLogger.logIt("Client socket from address " + clientSock.getInetAddress()
					        + " has been accepted");
				}
			}
		} catch (final IOException e) {
			ConsoleFileLogger.logIt("IOException occured in SkyWebServer main(): " + e);
		}
	}
}
